package com.sendtion.xrichtextdemo.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * SDCardUtil
 *
 * @since 2021-06-22
 */
public class SDCardUtil {
    private static final int INT_1024 = 1024;
    private static final int INT_4 = 4;
    private static final int INT_1 = -1;
    private static final int INT_4096 = 4096;

    /**
     * 根据Uri获取真实的文件路径
     *
     * @param context
     * @param uri
     * @return String
     */
    public static String getFilePathFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            FileDescriptor fr = helper.openFile(uri, "r");

            input = new FileInputStream(fr);
            File outputDir = context.getCacheDir();
            File outputFile = File.createTempFile("image", "tmp", outputDir);
            String tempFilename = outputFile.getCanonicalPath();
            output = new FileOutputStream(tempFilename);

            int read;
            byte[] bytes = new byte[INT_4096];
            while ((read = input.read(bytes)) != INT_1) {
                output.write(bytes, 0, read);
            }
            return new File(tempFilename).getCanonicalPath();
        } catch (FileNotFoundException e) {
            e.getMessage();
        } catch (IOException e) {
            e.getMessage();
        } catch (DataAbilityRemoteException e) {
            e.getMessage();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (Throwable t) {
                t.getCause();
            }
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return boolean
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        boolean isOk = false;
        if (file.isFile() && file.exists()) {
            isOk = file.delete();
        }
        return isOk;
    }
}
